package top.catblog.scheduledlearning.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import top.catblog.scheduledlearning.task.ScheduledOfTask;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class ScheduledConfig implements SchedulingConfigurer {

    @Autowired
    private ApplicationContext context;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        // 1.制造数据库存储了className
        Set<String> stringSet = new HashSet<>();
        stringSet.add("top.catblog.scheduledlearning.task.DynamicPrintTask");
        stringSet.add("top.catblog.scheduledlearning.task.Task1");

        // 2.遍历数据库 获取目标对象 Runable task
        stringSet.forEach(s -> {
            Class<?> clazz;
            Object task = null;
            try {
                clazz = Class.forName(s);
                task = context.getBean(clazz);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }catch (BeansException e) {
                throw new IllegalArgumentException(s + "未纳入到spring管理", e);
            }

            // 3. 断言判断：定时任务类必须实现ScheduledOfTask接口
            assert task != null;
            Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
            //4.执行定时任务注册机 启动定时任务注册
            scheduledTaskRegistrar.addTriggerTask(
             (Runnable) task,// 任务
             triggerContext -> new CronTrigger("*/2 * * * * ?").nextExecutionTime(triggerContext)//执行时间
            );
        });


    }


}
